package com.controller.system.advert;

import com.controller.base.BaseController;
import com.entity.system.*;
import com.service.system.advert.AdvertService;
import com.service.system.agent.AgentService;
import com.service.system.staticRole.StaticRoleService;
import com.util.Const;
import com.util.FileUtil;
import com.util.Image;
import com.util.LogUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @Author Alexpy
 * @CreateTime 2018/3/1 16:48
 * @Description
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "/advert")
public class AdvertController extends BaseController {

    @Autowired
    private AdvertService advertService;
    @Autowired
    private StaticRoleService staticRoleService;
    @Autowired
    private AgentService agentService;
    /**
     * 查询广告列表
     * @param req
     * @return
     */
    @RequestMapping(value = "/list", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> getAdvertList(HttpServletRequest req) {
        Map<String, Object> params = new HashMap();
        params.put("pageNum", req.getParameter("pageNum"));
        params.put("pageSize", req.getParameter("pageSize"));
        //广告类型
        if(StringUtils.isNotEmpty(req.getParameter("advertType"))){
            params.put("advertType",req.getParameter("advertType"));
        }
        //广告状态
        if(StringUtils.isNotEmpty(req.getParameter("state"))){
            params.put("state",req.getParameter("state"));
        }
        if(StringUtils.isNotEmpty(req.getParameter("startTime"))){
            params.put("startTime",req.getParameter("startTime"));
        }
        if(StringUtils.isNotEmpty(req.getParameter("endTime"))){
            params.put("endTime",req.getParameter("endTime"));
        }
        //代理商角色
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
        //代理商角色
        StaticUserRole sur = staticRoleService.getUserRoleByUserId(user.getId());
        StaticRole sr = staticRoleService.getRoleByRoleId(sur.getRoleId());
        if(sr != null && sr.getRoleCode().equals("VERSION_NEW_ROLE_AGENT")){
            //代理商权限
            AgentNew an = agentService.getAgentNewByUserId(user.getId());
            if(an != null) {
                if (1 == an.getAgentLevel()) {
                    params.put("area", an.getCountyCode());
                } else if (2 == an.getAgentLevel()) {
                    params.put("city", an.getCityCode());
                } else if (3 == an.getAgentLevel()) {
                    params.put("province", an.getProvinceCode());
                }
            }else {
                params.clear();
                LogUtil.info("*************你不是代理商*******************");
                params.put("code",Const.ERROR_CODE);
                params.put("message","查询失败");
                return params;
            }
        }

        Map<String, Object> result = advertService.getListByCondition(params);
        return result;
    }

    /**
     * 修改是否置顶
     * @param
     * @return
     */
    @RequestMapping(value = "/updateTopFlag",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> updateTopFlag(@RequestParam int topFlag, Long id){
        return advertService.updateTopFlag(topFlag,id);
    }

    /**
     * 审核不通过
     * @param request
     * @return
     */
    @RequestMapping(value = "/noThrough",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> noThrough(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.noThrough(Long.parseLong(id));
    }

    /**
     * 审核通过
     * @param request
     * @return
     */
    @RequestMapping(value = "/through",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> through(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.through(Long.parseLong(id));
    }

    /**
     * 查询banner列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/findBannerList",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findBannerList(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        map.put("pageSize",request.getParameter("pageSize"));
        map.put("pageNum",request.getParameter("pageNum"));
        map.put("startTime",request.getParameter("startTime"));
        map.put("endTime",request.getParameter("endTime"));
        return advertService.findBannerList(map);
    }

    /**
     * 删除banner
     * @param request
     * @return
     */
    @RequestMapping(value = "/delBanner",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> delBanner(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.delBanner(id);
    }

    /**
     * 修改banner
     * @param bannerConfig
     * @return
     */
    @RequestMapping(value = "/updateBanner",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> updateBanner(BannerConfig bannerConfig){
        return advertService.updateBanner(bannerConfig);
    }

    /**
     * 添加banner
     * @param file
     * @param bannerConfig
     * @return
     */
    @RequestMapping(value = "/addBanner",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> addBanner(MultipartFile file,BannerConfig bannerConfig){
        Map<String,Object> map = new HashMap<>();
        ResourceBundle rs = ResourceBundle.getBundle("environment");
        if(!file.isEmpty()){
            String contentType = file.getContentType();
            String suffix = FileUtil.getContentTypeSuffix(contentType);
            String url = rs.getString("base.resource.url")+"/image/upload";
            LogUtil.info(url);
            try {
                Image image = FileUtil.uploadBytesAndPostBinImage(file.getBytes(),suffix,url);
                if(image != null){
                    bannerConfig.setPicUrl(image.getUrl());
                }else {
                    map.put("code",Const.ERROR_CODE);
                    map.put("message","添加失败");
                    return map;
                }
            } catch (IOException e) {
                e.printStackTrace();
                map.put("code",Const.ERROR_CODE);
                map.put("message","添加失败");
                return map;
            }
        }
        return advertService.addBanner(bannerConfig);
    }

    /**
     * 查询走马灯列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/findNewsCycleList",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findNewsCycleList(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        map.put("pageSize",request.getParameter("pageSize"));
        map.put("pageNum",request.getParameter("pageNum"));
        if(StringUtils.isNotEmpty(request.getParameter("startTime"))){
            map.put("startTime",request.getParameter("startTime"));
        }
        if(StringUtils.isNotEmpty(request.getParameter("endTime"))){
            map.put("endTime",request.getParameter("endTime"));
        }
        if(StringUtils.isNotEmpty(request.getParameter("advertType"))){
            map.put("advertType",request.getParameter("advertType"));
        }
        return advertService.findNewsCycleList(map);
    }

    /**
     * 修改走马灯
     * @param newsCycle
     * @return
     */
    @RequestMapping(value = "/updateNewsCycle",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> updateNewsCycle(NewsCycle newsCycle){
        return advertService.updateNewsCycle(newsCycle);
    }

    /**
     * 删除走马灯
     * @param request
     * @return
     */
    @RequestMapping(value = "/delNewsCycle",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> delNewsCycle(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.delNewsCycle(Long.parseLong(id));
    }

    /**
     * 添加走马灯
     * @param newsCycle
     * @return
     */
    @RequestMapping(value = "/addNewsCycle",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> addNewsCycle(NewsCycle newsCycle){
        return advertService.addNewsCycle(newsCycle);
    }

    /**
     * 查询弹窗公告列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/findPopupAdvertList",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findPopupAdvertList(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        map.put("pageSize",request.getParameter("pageSize"));
        map.put("pageNum",request.getParameter("pageNum"));
        return advertService.findPopupAdvertList(map);
    }

    /**
     * 删除弹窗公告
     * @param request
     * @return
     */
    @RequestMapping(value = "/delPopupAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> delPopupAdvert(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.delPopupAdvert(Long.parseLong(id));
    }

    /**
     * 修改弹窗公告
     * @param popupAdvert
     * @return
     */
    @RequestMapping(value = "/updatePopupAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> updatePopupAdvert(PopupAdvert popupAdvert){
        return advertService.updatePopupAdvert(popupAdvert);
    }

    /**
     * 添加弹窗公告
     * @param file
     * @param popupAdvert
     * @return
     */
    @RequestMapping(value = "/addPopupAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> addPopupAdvert(MultipartFile file,PopupAdvert popupAdvert){
        Map<String,Object> map = new HashMap<>();
        ResourceBundle rs = ResourceBundle.getBundle("environment");
        if(!file.isEmpty()){
            String contentType = file.getContentType();
            String suffix = FileUtil.getContentTypeSuffix(contentType);
            String url = rs.getString("base.resource.url")+"/image/upload";
            LogUtil.info(url);
            try {
                Image image = FileUtil.uploadBytesAndPostBinImage(file.getBytes(),suffix,url);
                if(image != null){
                    popupAdvert.setPicUrl(image.getUrl());
                }else {
                    map.put("code",Const.ERROR_CODE);
                    map.put("message","添加失败");
                    return map;
                }
            } catch (IOException e) {
                e.printStackTrace();
                map.put("code",Const.ERROR_CODE);
                map.put("message","添加失败");
                return map;
            }
        }
        return advertService.addPopupAdvert(popupAdvert);
    }

    /**
     * 查询新用户福袋列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/findNewUserAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findNewUserAdvert(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        map.put("pageSize",request.getParameter("pageSize"));
        map.put("pageNum",request.getParameter("pageNum"));
        return advertService.findNewUserAdvert(map);
    }

    /**
     * 删除新用户福袋
     * @param request
     * @return
     */
    @RequestMapping(value = "/delNewUserAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> delNewUserAdvert(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.delNewUserAdvert(Long.parseLong(id));
    }

    /**
     * 添加新用户福袋
     * @param files
     * @param advert
     * @return
     */
    @RequestMapping(value = "/addNewUserAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> addNewUserAdvert(MultipartFile[] files, Advert advert){
        Map<String,Object> map = new HashMap<>();
        if(null != files && files.length > 0){
            ResourceBundle rs = ResourceBundle.getBundle("environment");
            List<String> list = new ArrayList<>();
            for(MultipartFile file : files){
                if(!file.isEmpty()){
                    String contentType = file.getContentType();
                    String suffix = FileUtil.getContentTypeSuffix(contentType);
                    String url = rs.getString("base.resource.url")+"/image/upload";
                    LogUtil.info(url);
                    try {
                        Image image = FileUtil.uploadBytesAndPostBinImage(file.getBytes(),suffix,url);
                        if(image != null){
                            list.add(image.getUrl());
                        }else {
                            map.put("code",Const.ERROR_CODE);
                            map.put("message","添加失败");
                            return map;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        map.put("code",Const.ERROR_CODE);
                        map.put("message","添加失败");
                        return map;
                    }
                }
            }
            map.put("photo",list);
            map.put("content",advert.getAdvertContent());
            advert.setAdvertContent(JSONObject.fromObject(map).toString());
            //shiro管理的session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
            advert.setUserId(user.getId());
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","添加失败");
            return map;
        }
        return advertService.addNewUserAdvert(advert);
    }

    /**
     * 修改新用户福袋
     * @param files
     * @param photos
     * @param advert
     * @return
     */
    @RequestMapping(value = "/updateNewUserAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> updateNewUserAdvert(MultipartFile[] files,String[] photos,Advert advert){
        Map<String,Object> map  = new HashMap<>();
        List<String> list = new ArrayList<>(Arrays.asList(photos));
        if(null != files && files.length > 0){
            ResourceBundle rs = ResourceBundle.getBundle("environment");
            for(MultipartFile file : files){
                if(!file.isEmpty()){
                    String contentType = file.getContentType();
                    String suffix = FileUtil.getContentTypeSuffix(contentType);
                    String url = rs.getString("base.resource.url")+"/image/upload";
                    LogUtil.info(url);
                    try {
                        Image image = FileUtil.uploadBytesAndPostBinImage(file.getBytes(),suffix,url);
                        if(image != null){
                            boolean isAdd = true;
                            for(int i = 0;i < list.size();i++){
                                if(StringUtils.isEmpty(list.get(i))){
                                    list.set(i,image.getUrl());
                                    isAdd = false;
                                    break;
                                }
                            }
                            if(isAdd){
                                list.add(image.getUrl());
                            }
                        }else {
                            map.put("code",Const.ERROR_CODE);
                            map.put("message","添加失败");
                            return map;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        map.put("code",Const.ERROR_CODE);
                        map.put("message","添加失败");
                        return map;
                    }
                }
            }
        }
        map.put("photo",list);
        map.put("content",advert.getAdvertContent());
        advert.setAdvertContent(JSONObject.fromObject(map).toString());
        return advertService.updateNewUserAdvert(advert);
    }

    /**
     * 查询广告余额
     * @param request
     * @return
     */
    @RequestMapping(value = "/findBalance",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findBalance(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.findBalance(Long.parseLong(id));
    }

    /**
     * 广告下线
     * @param request
     * @return
     */
    @RequestMapping(value = "/offlineAdvert",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> offlineAdvert(HttpServletRequest request){
        String id = request.getParameter("id");
        return advertService.offlineAdvert(Long.parseLong(id));
    }
}
